package com.example.rabbitmq.rpc;

import com.example.rabbitmq.constant.Constants;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RpcServer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setUsername(Constants.USERNAME);
        factory.setPassword(Constants.PASSWORD);
        factory.setPort(Constants.PORT);
        factory.setVirtualHost(Constants.VIRTUALHOST);
        //创建连接
        Connection connection = factory.newConnection();
        //创建通道
        Channel channel= connection.createChannel();

        DefaultConsumer consumer= new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("RPC服务端收到消息"+new String(body));
                //响应的数据
                String response="RPC服务端响应数据";

                AMQP.BasicProperties replyProperties=new AMQP.BasicProperties.Builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                channel.basicPublish("",properties.getReplyTo(),replyProperties,response.getBytes());
                channel.basicAck(envelope.getDeliveryTag(),false);

            }
        };

        channel.basicConsume(Constants.RPC_REQUEST_QUEUE, false, consumer);


    }
}
